﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Decision.IService;
using FantastPlatform.Framework;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Decision.Model;
using FantastPlatform.Framework.Model;
using Newtonsoft.Json;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class PatrolTaskViewService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IPatrolTaskService ptService = ServiceFactory.CreateService<IPatrolTaskService>();
            IPatrolTask patrolTask;
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            group.Conditions.Add(enableCondition);
            int totalCount = 0;
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    PatrolTaskView patrolTaskView = JsonToEntity<PatrolTaskView>(RepairString(data));
                    if (patrolTaskView.BeginTime > patrolTaskView.EndTime)
                    {
                        ReturnErrorMessage("调警指令开始时间不能大于结束时间");
                        return;
                    }
                    patrolTask = new PatrolTask();
                    patrolTask.Id = patrolTaskView.Id;
                    patrolTask.Name = patrolTaskView.Name;
                    patrolTask.Description = patrolTaskView.Description;
                    patrolTask.DefaultLeader = new Employee() { Id = patrolTaskView.DefaultLeader };
                    patrolTask.DutyLeader = new Employee() { Id = patrolTaskView.DutyLeader };
                    patrolTask.Require = patrolTaskView.Require;
                    patrolTask.BeginTime = patrolTaskView.BeginTime;
                    patrolTask.EndTime = patrolTaskView.EndTime;
                    patrolTask.TaskType = new PatrolTaskType() { Id = patrolTaskView.TaskType };
                    patrolTask.DutyOrganization = new Organization() { Id = patrolTaskView.DutyOrganization };
                    GetOrgPatrolTasks(patrolTask);
                    ptService.CreatePatrolTask(patrolTask);
                    ReturnSuccessMessage("保存调警指令成功");

                    break;
                case "Search":
                    group.Conditions.Add(new Condition() { Field = "Level", Type = typeof(Int32).FullName, Value1 = "1", Comparison = Comparisons.Eq, Relation = Relations.And });
                    IList<IPatrolTask> patrolTaskList = ptService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] patrolTaskObjList = (from p in patrolTaskList
                                                  select new
                                                  {
                                                      Id = p.Id,
                                                      Name = p.Name,
                                                      DutyOrganization = p.DutyOrganization == null ? "" : p.DutyOrganization.Name,
                                                      DefaultLeader = p.DefaultLeader == null ? "" : p.DefaultLeader.Name,
                                                      EndTime = p.EndTime == null ? "" : p.EndTime.ToString(),
                                                      BeginTime = p.BeginTime == null ? "" : p.BeginTime.ToString()
                                                  }).ToArray();
                    ReturnList(totalCount, patrolTaskObjList);
                    break;
                case "LoadPoints":
                    group.Conditions.Add(new Condition() { Field = "Parent.Id", Type = typeof(Int32).FullName, Value1 = Id, Comparison = Comparisons.Eq, Relation = Relations.And });
                    patrolTaskList = ptService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] patrolTaskPointObjList = (from p in patrolTaskList
                                                       select new
                                                       {
                                                           Name = p.Name,
                                                           SelfOrgPersonNum = p.SelfOrgPersonNum,
                                                           SelfOrgCar = p.SelfOrgCar,
                                                           OtherOrgName = p.OtherOrgName,
                                                           OtherOrgPersonNum = p.OtherOrgPersonNum
                                                       }).ToArray();
                    ReturnList(totalCount, patrolTaskPointObjList);
                    break;
                case "LoadDetail":
                    group.Conditions.Add(new Condition() { Field = "Parent.Id", Type = typeof(Int32).FullName, Value1 = Id, Comparison = Comparisons.Eq, Relation = Relations.And });
                    patrolTaskList = ptService.Search(group, null, PageSize, SelfPage, out totalCount);
                    object[] orgPatrolTaskObjList = GetViewList(patrolTaskList, false);
                    ReturnList(totalCount, orgPatrolTaskObjList);
                    break;
                case "LoadDetailNoId":
                    group.Conditions.Add(new Condition() { Field = "Parent.Id", Type = typeof(Int32).FullName, Value1 = Id, Comparison = Comparisons.Eq, Relation = Relations.And });
                    patrolTaskList = ptService.Search(group, null, PageSize, SelfPage, out totalCount);
                    orgPatrolTaskObjList = GetViewList(patrolTaskList, true);
                    ReturnList(totalCount, orgPatrolTaskObjList);
                    break;
                case "Get":
                    patrolTask = ptService.Get(Id);
                    object obj = GetViewObject(patrolTask, patrolTask.Id);
                    ReturnObj2(obj);
                    break;
                case "GetNoId":
                    patrolTask = ptService.Get(Id);
                    obj = obj = GetViewObject(patrolTask, 0);
                    ReturnObj2(obj);
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    ptService.Delete(idList);
                    ReturnSuccessMessage("删除成功");
                    break;
                case "SearchByCondition":


                    break;
                case "GetOrganization":

                    IOrganizationService orgService = ServiceFactory.CreateService<IOrganizationService>();
                    totalCount = 0;
                    IList<IOrganization> orgList = new List<IOrganization>();
                    group.Conditions.Add(new Condition() { Field = "Parent.Id", Type = typeof(Int32).FullName, Value1 = "1", Comparison = Comparisons.Like, Relation = Relations.And });
                    orgList = orgService.Search(group, null, int.MaxValue, 1, out totalCount);

                    object[] orgObjs = (from emp in orgList
                                        select new
                                        {
                                            Id = emp.Id,
                                            Name = emp.Name,
                                            Code = emp.Code
                                        }).ToArray();
                    ReturnList(orgObjs.Count(), orgObjs);
                    break;
                case "GetPatrolTaskType":

                    IPatrolTaskTypeService patrolTaskTypeService = ServiceFactory.CreateService<IPatrolTaskTypeService>();
                    totalCount = 0;
                    IList<IPatrolTaskType> pttList = new List<IPatrolTaskType>();
                    pttList = patrolTaskTypeService.Search(group, null, int.MaxValue, 1, out totalCount);
                    object[] pttObjs = (from emp in pttList
                                        select new
                                        {
                                            Id = emp.Id,
                                            Name = emp.Name,
                                            Code = emp.Code
                                        }).ToArray();
                    ReturnList(pttObjs.Count(), pttObjs);
                    break;
            }

        }

        private  object[] GetViewList(IList<IPatrolTask> patrolTaskList, bool isNoId)
        {
            object[] orgPatrolTaskObjList = (from p in patrolTaskList
                                             select new
                                             {
                                                 Id = isNoId ? 0 : p.Id,
                                                 ExecOrganization = p.ExecOrganization != null ? p.ExecOrganization.Id : 0,
                                                 BeginTime = p.BeginTime == null ? "" : p.BeginTime.Value.Hour.ToString() + ":" + p.BeginTime.Value.Minute.ToString(),
                                                 EndTime = p.EndTime == null ? "" : p.EndTime.Value.Hour.ToString() + ":" + p.EndTime.Value.Minute.ToString(),
                                                 Points = JsonConvert.SerializeObject((from c in p.Children
                                                                                       where c.Enable == true
                                                                                       select new
                                                                                       {
                                                                                           Id = isNoId ? 0 : c.Id,
                                                                                           Name = c.Name,
                                                                                           SelfOrgPersonNum = c.SelfOrgPersonNum,
                                                                                           SelfOrgCar = c.SelfOrgCar,
                                                                                           OtherOrgName = c.OtherOrgName,
                                                                                           OtherOrgPersonNum = c.OtherOrgPersonNum
                                                                                       }).ToArray()
                                                                                           ),
                                             }).ToArray();
            return orgPatrolTaskObjList;
        }

        private object GetViewObject(IPatrolTask patrolTask, int Id)
        {
            object obj = new
            {
                Id = Id,
                Name = patrolTask.Name,
                Description = patrolTask.Description,
                DefaultLeaderName = patrolTask.DefaultLeader.Id + "|" + patrolTask.DefaultLeader.Name,
                DutyLeaderName = patrolTask.DutyLeader != null ? patrolTask.DutyLeader.Id + "|" + patrolTask.DutyLeader.Name : "",
                Require = patrolTask.Require,
                BeginTime = patrolTask.BeginTime,
                EndTime = patrolTask.EndTime,
                TaskType = patrolTask.TaskType.Id,
                DutyOrganization = patrolTask.DutyOrganization.Id

            };
            return obj;
        }
        private void GetOrgPatrolTasks(IPatrolTask patrolTask)
        {
            string endTime = Request["EndTime"];
            string startTime = Request["StartTime"];
            string Data1 = "";
            if (!string.IsNullOrEmpty(Request["data1"]))
            {
                Data1 = Request["data1"];
            }
            OrgPatrolTaskListView orgPatrolTaskListView = JsonToEntity<OrgPatrolTaskListView>(RepairString(Data1));
            if (orgPatrolTaskListView != null)
            {
                patrolTask.Children = new List<IPatrolTask>();
                foreach (PatrolTaskView s in orgPatrolTaskListView.OrgPatrolTaskList)
                {
                    
                    IPatrolTask orgPatrolTask = new PatrolTask();
                    orgPatrolTask.Id = s.Id;
                    orgPatrolTask.Name = s.Name;
                    orgPatrolTask.Description = s.Description;
                    orgPatrolTask.DutyOrganization = new Organization() { Id = patrolTask.DutyOrganization.Id };
                    orgPatrolTask.ExecOrganization = new Organization() { Id = s.ExecOrganization };
                    orgPatrolTask.TaskType = new PatrolTaskType() { Id = patrolTask.TaskType.Id };
                    orgPatrolTask.DefaultLeader = new Employee() { Id = s.DefaultLeader == 0 ? patrolTask.DefaultLeader.Id : s.DefaultLeader };
                    orgPatrolTask.BeginTime = new DateTime(patrolTask.BeginTime.Value.Year,
                                patrolTask.BeginTime.Value.Month, patrolTask.BeginTime.Value.Day,
                                DateTime.Parse(s.BeginTimeStr).Hour, DateTime.Parse(s.BeginTimeStr).Minute, DateTime.Parse(s.BeginTimeStr).Second);
                    orgPatrolTask.EndTime = new DateTime(patrolTask.EndTime.Value.Year,
                                patrolTask.EndTime.Value.Month, patrolTask.EndTime.Value.Day,
                                DateTime.Parse(s.EndTimeStr).Hour, DateTime.Parse(s.EndTimeStr).Minute, DateTime.Parse(s.EndTimeStr).Second);
                    if (orgPatrolTask.BeginTime > orgPatrolTask.EndTime)
                    {
                        ReturnErrorMessage("调警指令开始时间不能大于结束时间");
                        return;
                    }
                    orgPatrolTask.Require = s.Require;
                    orgPatrolTask.Children = new List<IPatrolTask>();
                    foreach (PatrolTaskView pt in s.Points)
                    {
                        IPatrolTask pointTask = new PatrolTask();
                        pointTask.Id = pt.Id;
                        pointTask.Name = pt.Name;
                        pointTask.SelfOrgPersonNum = pt.SelfOrgPersonNum;
                        pointTask.OtherOrgPersonNum = pt.OtherOrgPersonNum;
                        pointTask.SelfOrgCar = pt.SelfOrgCar;
                        pointTask.OtherOrgName = pt.OtherOrgName;
                        orgPatrolTask.Children.Add(pointTask);
                    }
                    patrolTask.Children.Add(orgPatrolTask);
                }
            }
        }
        public class OrgPatrolTaskListView
        {
            //public int Id { get; set; }
            public List<PatrolTaskView> OrgPatrolTaskList { get; set; }
        }
        public class PatrolTaskView
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public int DutyOrganization { get; set; }
            public int ExecOrganization { get; set; }
            public int TaskType { get; set; }
            public int DefaultLeader { get; set; }
            public int DutyLeader { get; set; }
            public DateTime? BeginTime { get; set; }
            public DateTime? EndTime { get; set; }
            public string BeginTimeStr { get; set; }
            public string EndTimeStr { get; set; }
            public string Require { get; set; }
            public string SelfOrgPersonNum { get; set; }
            public string OtherOrgPersonNum { get; set; }
            public string OtherOrgPerson { get; set; }
            public string SelfOrgCar { get; set; }
            public string OtherOrgName { get; set; }
            public List<PatrolTaskView> Points { get; set; }
        }
        public class PatrolTaskPointView
        {
            public int Id { get; set; }
            public string Station { get; set; }
            public string Office { get; set; }
            public string Phone { get; set; }
            public string Phone1 { get; set; }
            public string Home { get; set; }
        }
    }
}